<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;


use app\admin\model\DeviceBind;
use app\admin\model\Schoole;
use app\admin\model\Student;
use think\Db;
use think\Exception;
use think\facade\Request;

/**
 * 学生管理-服务类
 * @author 牧羊人
 * @since: 2024/06/25
 * Class StudentService
 * @package app\admin\service
 */
class StudentService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new Student();
        // 解析Token获取用户ID
        $token = request()->header("Authorization");
        $token = str_replace("Bearer ", null, $token);
        $jwt = new \Jwt();
        $this->userId = $jwt->verifyToken($token);
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2024/06/25
     * @author 牧羊人
     */
    public function getList($page = 0, $limit = 0)
    {
        // 查询条件
        $map = [];
        //$map[] = ['s.status', '=', 1];
        //地区
        $param = request()->param();
        $province_code = getter($param, "province_code");
        $city_code = getter($param, "city_code");
        $district_code = getter($param, "district_code");
        $streets_code = getter($param, "streets_code");
        if ($streets_code) {
            $map[] = ['schoole.streets_code', '=', $streets_code];
        } elseif ($district_code) {
            $map[] = ['schoole.district_code', '=', $district_code];
        } elseif ($city_code) {
            $map[] = ['schoole.city_code', '=', $city_code];
        } elseif ($province_code) {
            $map[] = ['schoole.province_code', '=', $province_code];
        }
        $schoole_id = request()->param('schoole_id', '');
        if ($schoole_id) {
            $map[] = ["s.schoole_id", "=", $schoole_id];
        }
        $grade_id = request()->param('grade_id', '');
        if ($grade_id) {
            $map[] = ["s.grade_id", "=", $grade_id];
        }
        $class_id = request()->param('class_id', '');
        if ($class_id) {
            $map[] = ["s.class_id", "=", $class_id];
        }

        $gender = request()->param('gender', '');
        if ($gender !== '') {
            $map[] = ["s.gender", "=", $gender];
        }

        // 适用于：班级管理->班级名单列表，导出
        $keyword = request()->param('keyword', '');
        if ($keyword) $map[] = ["s.imei|s.name|s.id_card|s.student_no|s.sim_no|s.phone", "like", '%' . $keyword . '%'];

        $keywords = request()->param('keywords', '');
        if ($keywords) {
            $map[] = ["s.imei|s.name|s.id_card|s.student_no|s.sim_no|s.phone", "like", '%' . $keywords . '%'];
        }
        $page = $page ?: request()->param('page', 1);
        $limit = $limit ?: request()->param('limit', 20);

        $teacher = getTeacher( $this->userId);
        if($teacher){
            $clsses = Db::table('think_class')->where('find_in_set(' . $teacher['id']. ',teacher_ids)')->select();
           // print_r($clsses);
            if($clsses){
                $map[]  = ['grade_id','in',array_column($clsses,'grade_id')];
                $map[]  = ['class_id','in',array_column($clsses,'class_key')];
            }
        }

        $schoolRole = SchoolRoleMap($this->userId,'schoole_id');
        if($schoolRole){
            $map[] = $schoolRole;
        }

        $data = db('student')
            ->alias('s')
            ->field('s.*, schoole.title as schoole_name')
            ->join('schoole schoole', 's.schoole_id = schoole.id', 'left')
            ->where($map)
            ->where('s.mark = 1')
            ->order('id desc')
            ->paginate($limit)
            ->each(function ($item) {
                $item['grade_name'] = db('grade')->where(['schoole_id' => $item['schoole_id'], 'grade_key' => $item['grade_id']])->value('title');
                $item['class_name'] = db('class')->where(['schoole_id' => $item['schoole_id'], 'grade_id' => $item['grade_id'], 'class_key' => $item['class_id']])->value('title');
                $item['avatar'] = $item['avatar'] ?: ($item['gender'] == 2 ? '/n2.jpg' : '/n1.png');
                return $item;
            })
            ->toArray();
        $res = [
            "msg" => '操作成功',
            "code" => 0,
            "count" => $data['total'],
            "data" => $data['data'],
        ];
        return $res;
    }

    //新增、编辑
    public function edit()
    {
        // 请求参数
        request()->filter('trim');
        $data = request()->param();
        $id = getter($data, "id", 0); // ID
        if (!isset($data['imei']) || !$data['imei']) {
            return message("缺少设备IMEI码", false);
        }
        if (!isset($data['schoole_id']) || !$data['schoole_id']) {
            return message("缺少schoole_id", false);
        }
        //查询设备码是否存在
        $imei = db('device_imei')
            ->where("imei", '=', $data['imei'])
            ->where("delete_time IS NULL")
            ->find();
        if (!$imei) {
            return message("设备码不存在", false);
        }

        //新增
        if (empty($id)) {
            //验证imei有没有被使用
            $info = $this->model
                //->where("status", '=', 1)
                ->where("imei", '=', $data['imei'])
                //->where('mark',1)
                ->find();
            if ($info) {
                return message("设备IMEI码已被使用", false);
            }
        } else {
            // 用户名重复性验证
            //验证imei有没有被使用
            $info = $this->model
                ->where("imei", '=', $data['imei'])
                ->where("id", '<>', $id)
                ->where('mark',1)
                ->find();
            if ($info) {
                return message("设备IMEI码已被使用", false);
            }
        }

        //身份证号验证
        if (isset($data['id_card']) && $data['id_card']) {
            if (!is_idcard($data['id_card'])) {
                return message("身份证号码格式错误", false);
            }
        }
        //手机号验证
        if (isset($data['phone']) && $data['phone']) {
            if (!is_mobile($data['phone'])) {
                return message("手机号码格式错误", false);
            }
        }
        if (isset($data['relatives_phone']) && $data['relatives_phone']) {
            if (!is_mobile($data['relatives_phone'])) {
                return message("紧急联系人手机号码格式错误", false);
            }
        }
        //SIM卡号验证
        if (isset($data['sim_no']) && $data['sim_no']) {
            if (!is_mobile($data['sim_no'])) {
                return message("SIM卡号格式错误", false);
            }
        }
        if(!isset($data['grade_id']) || !$data['grade_id']){
            return message("年级必填", false);
        }
        if(!isset($data['class_id']) || !$data['class_id']){
            return message("班级必填", false);
        }


        // 头像处理
        $avatar = getter($data, 'avatar');
        $data['avatar'] = $avatar;
        if (strpos($avatar, (string)"temp")) {
            $data['avatar'] = save_image($avatar, 'user');
        } else {
            $data['avatar'] = str_replace(IMG_URL, "", $data['avatar']);
        }

        // 出生日期
        /*if ($data['birthday']) {
            $data['birthday'] = strtotime($data['birthday']);
        }*/


        Db::startTrans();
        try {
            $error = "";
            $result = $this->model->edit($data, $error);
            if (!$result) {
                throw new Exception($error);
            }
            //是否绑定过
            $bind_check = DeviceBind::where(['imei' => $data['imei']])->count();
            //没有绑定，执行绑定
            if (!$bind_check) {
                $extra['device_alias'] = '未设置';
                $extra['relation'] = '未设置';
                $extra['default_show'] = 0;
                $extra['stu_id'] = $id;
                $bind_res = (new DeviceBindService())->add(0, $extra);
                if ($bind_res['code'] != 0) {
                    throw new Exception($bind_res['msg'] ?? '绑定异常');
                }
            } else {
                DeviceBind::where(['imei' => $data['imei']])->update(['stu_id' => $id]);
            }
            Db::commit();

        } catch (\Throwable $e) {
            Db::rollback();
            return message($e->getMessage(), false);
        }


        return message();
    }

    //删除
   /* public function delete()
    {
        $id = request()->param('id', '0');
        //$result = db('student')->where(['id' => $id])->update(['status' => 2, 'update_time' => time()]);
        $result = db('student')->where(['id' => $id])->delete();
        if (!$result) {
            return message('操作失败', false);
        }
        return message();
    }*/
    public function delete()
    {
        // 参数
        $param = request()->param();

        // 记录ID
        $ids = getter($param, "id");
        if (empty($ids)) {
            return message("记录ID不能为空", false);
        }

        if (is_array($ids)) {
            // 批量删除
            $result = $this->model->deleteDAll($ids);
            $this->model->where('id', 'in', $ids)->update(['schoole_id' => 0,'grade_id' => 0,'class_id' => 0,]);
            if (!$result) {
                return message("批量删除失败", false);
            }

            return message("批量删除成功");
        } else {
            $this->model->where('id',$ids)->update(['schoole_id' => 0,'grade_id' => 0,'class_id' => 0,]);
            // 单个删除
            $result = $this->model->drop($ids);
            if (!$result) {
                return message('删除失败', false);
            }

            return message('删除成功');
        }
    }
    //根据学校获取年级
    public function getGrade()
    {
        // 查询条件
        $map = [];
        $schoole_id = request()->param('schoole_id', '');
        if (!$schoole_id) {
            return message("缺少schoole_id", false);
        }
        $map[] = ["schoole_id", "=", $schoole_id];
        $map[] = ["mark", "=", 1];

        $data = db('grade')
            ->field('grade_key as id, title')
            ->where($map)
            ->order('grade_key asc')
            ->group('grade_key')
            ->select();
        $res = [
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
        ];
        return $res;
    }

    //根据年级获取班级
    public function getClass()
    {
        // 查询条件
        $map = [];
        $schoole_id = request()->param('schoole_id', '');
        if (!$schoole_id) {
            return message("缺少schoole_id", false);
        }
        $grade_id = request()->param('grade_id', '');
        if (!$grade_id) {
            return message("缺少grade_id", false);
        }
        $map[] = ["schoole_id", "=", $schoole_id];
        $map[] = ["grade_id", "=", $grade_id];
        $map[] = ["mark", "=", 1];

        $data = db('class')
            ->field('class_key as id, title')
            ->where($map)
            ->order('class_key asc')
            ->group('class_key')
            ->select();
        $res = [
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
        ];
        return $res;
    }

    //获取性别
    public function getGender()
    {
        $data = [
            [
                'type' => 1,
                'title' => '男'
            ],
            [
                'type' => 2,
                'title' => '女'
            ]
        ];
        return message("操作成功", true, $data);
    }

    //左侧省市县街道学校 5级树状
    public function schooleMenu()
    {
        $list = $this->model->schooleMenu();
        return message("操作成功", true, $list);
    }

    /**
     * 导入Excel
     */
    public function importExcel()
    {
        $schoole_id = request()->param('schoole_id', '');
        if (!$schoole_id) {
            return message('缺少schoole_id', false);
        }
        if (!Schoole::where(['id' => $schoole_id])->value('id')) {
            return message('学校不存在', false);
        }

        // 检查文件扩展名
        $file = $_FILES['file'];
        if (!$file) return message("请上传文件", false);
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        if (strtolower($extension) !== 'xlsx')
            return message("上传的文件必须是 .xlsx 格式。", false);

        $error = "";
        // 上传文件(非图片)
        $result = upload_file('file', 'student/import/', $error);
        if (!$result) {
            return message($error, false);
        }
        // 文件路径
        $filePath = FILE_PATH . $result;
        if (!file_exists($filePath)) {
            return message("文件不存在", false);
        }
        // 读取文件
        $objPHPExcel = \PHPExcel_IOFactory::load($filePath); //获取sheet表格数目
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected); //获取表格行数
        $activeSheet = $objPHPExcel->getActiveSheet();
        $rowCount = $activeSheet->getHighestRow(); //获取表格列数
        $columnCount = $activeSheet->getHighestColumn();
        $totalNum = $rowCount - 2;
        //验证文件内容
        if ($totalNum < 1) return message("请填写数据后上传", false);
        if ($columnCount != 'J') return message("请不要更改模板文件格式，填写数据后上传", false);

        $dataArr = array();
        $gender_arr = [
            '男' => 1,
            '女' => 2,
        ];
        $imei_arr = [];
        // 循环读取行数据
        for ($row = 3; $row <= $rowCount; $row++) {
            // 获取列值
            $imei = trim($activeSheet->getCell("I" . $row)->getValue());
            if (!$imei) return message(sprintf('第%s行，设备IMEI未填写', $row), false);
            $imei_id = db('device_imei')->where(['imei' => $imei])->value('id');
            if (!$imei_id) return message(sprintf('第%s行，设备IMEI：%s 不存在', $row, $imei), false);
            $student_id = db('student')->where(['imei' => $imei])->value('id');
            if ($student_id) return message(sprintf('第%s行，设备IMEI：%s 已绑定学生', $row, $imei), false);
            if (in_array($imei, array_keys($imei_arr)))
                return message(sprintf('第%s行，设备IMEI：%s ，与第%s行重复', $row, $imei, $imei_arr[$imei]), false);
            $imei_arr[$imei] = $row;

            //年级
            $grade_id = 0;
            $grade = trim($activeSheet->getCell("E" . $row)->getValue());
            if ($grade) {
                $grade_id = db('grade')->where(['schoole_id' => $schoole_id, 'title' => $grade])->value('grade_key');
                if (!$grade_id) return message(sprintf('第%s行，年级：%s 不存在', $row, $grade), false);
            }
            //班级
            $class_id = 0;
            $class = trim($activeSheet->getCell("F" . $row)->getValue());
            if ($class) {
                $class_id = db('class')->where(['schoole_id' => $schoole_id, 'grade_id' => $grade_id, 'title' => $class])->value('class_key');
                if (!$class_id) return message(sprintf('第%s行，班级：%s 不存在', $row, $class), false);
            }
            $name = trim($activeSheet->getCell("A" . $row)->getValue());
            if (!$name) return message(sprintf('第%s行，姓名未填写', $row), false);

            $student_no = trim($activeSheet->getCell("B" . $row)->getValue());
            $id_card = trim($activeSheet->getCell("C" . $row)->getValue());
            $gender = trim($activeSheet->getCell("D" . $row)->getValue());
            $gender = $gender_arr[$gender] ?? 0;
            $phone = trim($activeSheet->getCell("G" . $row)->getValue());
            $relatives_phone = trim($activeSheet->getCell("H" . $row)->getValue());
            $sim_no = trim($activeSheet->getCell("J" . $row)->getValue());
            if ($id_card && strlen($id_card) != 18) return message(sprintf('第%s行，身份证号：%s 格式错误', $row, $id_card), false);
            if ($phone && strlen($phone) != 11) return message(sprintf('第%s行，手机号：%s 格式错误', $row, $phone), false);
            if ($relatives_phone && strlen($relatives_phone) != 11) return message(sprintf('第%s行，紧急联系人手机号：%s 格式错误', $row, $relatives_phone), false);

            $temp = compact('imei', 'name', 'student_no', 'id_card', 'gender', 'grade_id', 'class_id', 'schoole_id', 'phone', 'relatives_phone', 'sim_no');
            $temp['create_time'] = time();
            $temp['update_time'] = time();
            $temp['create_user'] = $this->userId;
            $temp['update_user'] = $this->userId;
            $dataArr[] = $temp;
        }

        Db::startTrans();
        try {
            $this->model->saveAll($dataArr);

            $imei = array_column($dataArr, 'imei');
            $imeiBind = DeviceBind::where('imei', 'in', $imei)->column('imei');
            $studentImeiData = $this->model->where('imei', 'in', $imei)->column('imei', 'id');
            foreach ($studentImeiData as $studentId => $studentImei) {
                if (in_array($studentImei, $imeiBind)) {
                    DeviceBind::where(['imei' => $studentImei])->update(['stu_id' => $studentId]);
                } else {
                    DeviceBind::create(
                        [
                            'imei'         => $studentImei,
                            'user_id'      => 0,
                            'device_alias' => '未设置',
                            'relation'     => '未设置',
                            'default_show' => 0,
                            'stu_id'       => $studentId,
                            'create_time'  => time(),
                            'update_time'  => time(),
                            'is_admin'     => 1
                        ]
                    );
                }
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('导入学生异常：' . $e->getTraceAsString(), 'error');
            return message($e->getMessage(), false);
        }
        return message("本次成功导入{$totalNum}条数据", true);
    }


    /**
     * 导出Excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function exportExcel()
    {
        set_time_limit(0);
        $export_type = request()->param('export_type', 0);
        $schoole_id = request()->param('schoole_id', '');
        $schoole_name = '';

        // 获取导出的数据源
        $res = $this->getList(1, 20000);
        $list = $res['data'];

        // 实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        // 激活当前的sheet表
        $activeSheet = $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $activeSheet->setCellValue('A1', '姓名')
            ->setCellValue('B1', '学号')
            ->setCellValue('C1', '身份证号')
            ->setCellValue('D1', '性别')
            ->setCellValue('E1', '学校')
            ->setCellValue('F1', '年级')
            ->setCellValue('G1', '班级')
            ->setCellValue('H1', '电话')
            ->setCellValue('I1', '紧急联系人电话')
            ->setCellValue('J1', '设备IMEI')
            ->setCellValue('K1', 'SIM卡号')
            ->setCellValue('L1', '创建时间');

        // 设置单元格宽度
        $activeSheet->getColumnDimension('A')->setWidth(20);
        $activeSheet->getColumnDimension('B')->setWidth(20);
        $activeSheet->getColumnDimension('C')->setWidth(20);
        $activeSheet->getColumnDimension('D')->setWidth(20);
        $activeSheet->getColumnDimension('E')->setWidth(20);
        $activeSheet->getColumnDimension('F')->setWidth(20);
        $activeSheet->getColumnDimension('G')->setWidth(20);
        $activeSheet->getColumnDimension('H')->setWidth(20);
        $activeSheet->getColumnDimension('I')->setWidth(20);
        $activeSheet->getColumnDimension('J')->setWidth(20);
        $activeSheet->getColumnDimension('K')->setWidth(20);
        $activeSheet->getColumnDimension('L')->setWidth(20);

        //'s.*, schoole.title as schoole_name, grade.title as grade_name, class.title as class_name'
        // 循环刚取出来的数组，将数据逐一添加到excel表格
        $gender_arr = [
            '1' => '男',
            '2' => '女',
        ];
        for ($i = 0; $i < count($list); $i++) {
            $gender = $gender_arr[$list[$i]['gender']] ?? '';
            $activeSheet->setCellValue('A' . ($i + 2), $list[$i]['name']);
            $activeSheet->setCellValue('B' . ($i + 2), $list[$i]['student_no']);
            $activeSheet->setCellValue('C' . ($i + 2), $list[$i]['id_card']);
            $activeSheet->setCellValue('D' . ($i + 2), $gender);
            $activeSheet->setCellValue('E' . ($i + 2), $list[$i]['schoole_name']);
            $activeSheet->setCellValue('F' . ($i + 2), $list[$i]['grade_name']);
            $activeSheet->setCellValue('G' . ($i + 2), $list[$i]['class_name']);
            $activeSheet->setCellValue('H' . ($i + 2), $list[$i]['phone']);
            $activeSheet->setCellValue('I' . ($i + 2), $list[$i]['relatives_phone']);
            $activeSheet->setCellValue('J' . ($i + 2), $list[$i]['imei']);
            $activeSheet->setCellValue('K' . ($i + 2), $list[$i]['sim_no']);
            $activeSheet->setCellValue('L' . ($i + 2), date('Y-m-d H:i:s', $list[$i]['create_time']));
            $schoole_name = $list[$i]['schoole_name'];
        }
        // 设置保存的Excel表格名称
        $filename = $schoole_name . '_学生导出_' . date('YmdHis', time()) . ".xlsx";
        // 设置当前激活的sheet表格名称
        $activeSheet->setTitle('Sheet1');

        if ($export_type) { //直接浏览器输出
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename);
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');
            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            return;
        }

        // 保存本地文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $file_dir = UPLOAD_TEMP_PATH . "/" . $schoole_id . "/";
        $savePath = $file_dir . $filename;
        // 检测文件路径是否存在,不存在则创建
        if (!file_exists($file_dir)) {
            mkdirs($file_dir, 0777, true);
        }
        $objWriter->save($savePath);

        // 文件地址
        $filePath = get_image_url(str_replace(PUBLIC_PATH, "", $savePath));
        return message("操作成功", true, $filePath);
    }

    //获取学生轨迹
    public function getLocation()
    {
        // 查询条件
        $student_map = [];
        $imei = request()->param('imei', '');
        if ($imei) {
            $student_map[] = ["s.imei", "=", $imei];
        } else {
            return message("缺少imei", false);
        }
        //学生信息
        $student_info = db('student')
            ->alias('s')
            ->join('device_imei di', 'di.imei = s.imei', 'left')
            ->join('schoole schoole', 's.schoole_id = schoole.id', 'left')
            ->join('grade grade', 's.grade_id = grade.id', 'left')
            ->join('class class', 's.class_id = class.id', 'left')
            ->field('s.*, schoole.title as schoole_name, grade.title as grade_name, class.title as class_name, di.electricity_level, di.is_active')
            ->where($student_map)
            ->find();
        if (!$student_info) return message("学生不存在", false);
        //（当前）最后定位
        $now_location = db('device_location')->where(['imei' => $student_info['imei']])->order('create_time', 'desc')->find();
        $student_info['lng'] = $now_location['lng'] ?? '';
        $student_info['lat'] = $now_location['lat'] ?? '';
        $student_id = $student_info['id'];

        //轨迹信息
        $belong_time = request()->param('belong_time', date('Y-m-d'));
        if ($belong_time && strtotime($belong_time)) {
            $stime = strtotime($belong_time);
            $etime = $stime + 60 * 60 * 24 - 1;
            $dl_map[] = ["create_time", "between", [$stime, $etime]];
        }
        $location_list = db('device_location')
            ->where(['imei' => $imei])
            ->where($dl_map)
            ->order('create_time', 'asc')
            ->select();

        //当日步数、行程
        $day_trip = db('device_step_records')
            ->where(['imei' => $imei])
            ->where([["date", "between", [date('Y-m-d', $stime), date('Y-m-d', $stime)]]])
            ->group('imei')
            ->find();
        if(!$day_trip){
            $day_trip = [
                "id" =>0,
                "imei" => $imei,
                "device_id" => 0,
                "date" => date('Y-m-d', $stime),
                "step_count" => 0,
                "created_at" => date('Y-m-d H:i:s', time()),
                "updated_at" => date('Y-m-d H:i:s', time())
            ];
        }

        //近一周步数、行程
        $seven_days_time = 60 * 60 * 24 * 6;
        $week_trip = db('device_step_records')
            ->where(['imei' => $imei])
            ->where([["date", "between", [date('Y-m-d', $stime - $seven_days_time), date('Y-m-d', $stime)]]])
            ->group('date')
            ->order('date asc')
            ->select();
        if(!$week_trip){
            //模拟近一周步数、行程
            $week_trip = [];
            $start_time = date('Y-m-d', $stime - $seven_days_time);
            for ($i = 0; $i < 7; $i++) {
                $week_trip[] = [
                    "id" => $i+1,
                    "imei" => $imei,
                    "device_id" => 0,
                    "date" => date('Y-m-d', strtotime($start_time) + $i * 60 * 60 * 24),
                    "step_count" => 0,
                    "created_at" => date('Y-m-d H:i:s', time()),
                    "updated_at" => date('Y-m-d H:i:s', time())
                ];
            }
        }

        $imeiInfo = getImeiInfo($imei);
        //print_r($imeiInfo);
        $student_info['is_active'] = $imeiInfo['online'];
        $student_info['electricity_level'] = $imeiInfo['battery'];

        return message("操作成功", true, ['student_info' => $student_info, 'location_list' => $location_list, 'day_trip' => $day_trip, 'week_trip' => $week_trip]);
    }


}
